package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.ChooseLikeCarActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.car.LikeCarAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.ModifyMileBoardCast;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshAndSwipeMenuListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenu;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenuCreator;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenuItem;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenuListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/10/27.
 */
public class LikeCarActivity extends BaseActivity implements NetDataJson.OnNetDataJsonListener {

    private PullToRefreshAndSwipeMenuListView pullToRefreshAndSwipeMenuListView;

    private SwipeMenuListView swipeMenuListView;

    private NetDataJson netWork;

    private LoadingDialog loadingDialog;

    private List<CarSource> carSources;

    private LikeCarAdapter likeCarAdapter;

    private NetDataJson setCarNetDataJson;

    private static final int REQUEST_CAR = 0X1211;

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.like_car_layout);

        netWork = new NetDataJson(this);
        setTitle("管理爱车");
        initView();
        initData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
            netWork = null;
        }
    }

    private void initData() {
        loadingDialog.show();
        carSources.clear();
        netWork.setUrl(API.like_car_list);
        netWork.request("get");
    }


    private void initView() {
        carSources = new ArrayList<CarSource>();
        loadingDialog = new LoadingDialog(this, "加载中");
        imageView = (ImageView) this.findViewById(R.id.right_accuracy);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.add_car);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LikeCarActivity.this, ChooseLikeCarActivity.class);
                if (likeCarAdapter.getCount() > 0) {
                    intent.putExtra("isdefalut", false);
                } else {
                    intent.putExtra("isdefalut", true);
                }
                startActivityForResult(intent, REQUEST_CAR);
            }
        });
        setCarNetDataJson = new NetDataJson(onNetDataJsonListener);
        pullToRefreshAndSwipeMenuListView = (PullToRefreshAndSwipeMenuListView) this.findViewById(R.id.listview);
        pullToRefreshAndSwipeMenuListView.setMode(PullToRefreshBase.Mode.DISABLED);
        pullToRefreshAndSwipeMenuListView.setScrollingWhileRefreshingEnabled(false);
        swipeMenuListView = pullToRefreshAndSwipeMenuListView.getRefreshableView();
        likeCarAdapter = new LikeCarAdapter(carSources, this);
        initSwipeMenu();
        swipeMenuListView.setAdapter(likeCarAdapter);
    }

    public void setDefalutCar(int id) {
        loadingDialog.show();
        setCarNetDataJson.setUrl(API.set_like_car);
        setCarNetDataJson.addParam("my_car_id", id);
        setCarNetDataJson.request("post");


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CAR) {
                initData();
            }
        }
    }

    NetDataJson.OnNetDataJsonListener onNetDataJsonListener = new NetDataJson.OnNetDataJsonListener() {
        @Override
        public void onDataJsonError(String errorMessage) {
            loadingDialog.dismiss();
            Toast.makeText(LikeCarActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDataJsonUpdate(JSONObject json) {
            if (MainActivity.main != null)
                MainActivity.main.mUserHomeFragment.refresh();
            Intent intent = new Intent(ModifyMileBoardCast.MODIFY_MILE_ACTION);
            intent.putExtra("action" , "manager");
            sendBroadcast(intent);
            initData();
        }
    };

    private void initSwipeMenu() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                int width = getWindowManager().getDefaultDisplay().getWidth();
                SwipeMenuItem item1 = new SwipeMenuItem(LikeCarActivity.this);
                item1.setBackground(R.drawable.delete_bg);
                item1.setTitle("删除");
                item1.setTitleColor(Color.WHITE);
                item1.setTitleSize(15);
                item1.setWidth(width / 5);
                menu.addMenuItem(item1);
            }
        };
        swipeMenuListView.setMenuCreator(creator);
        swipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                if (carSources.get(position).is_default) {
                    Toast.makeText(LikeCarActivity.this, "不能删除默认爱车", Toast.LENGTH_SHORT).show();
                    return;
                }
                loadingDialog.show();
                setCarNetDataJson.setUrl(API.cancle_like_car);
                setCarNetDataJson.addParam("my_car_id", carSources.get(position).mId);
                setCarNetDataJson.request("post");
            }
        });
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        loadingDialog.dismiss();
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        loadingDialog.dismiss();
        try {
            JSONArray jsonArray = json.getJSONArray("cars");
            if (jsonArray.length() > 0) {
                carSources.clear();
            } else {
                findViewById(R.id.no_data).setVisibility(View.VISIBLE);
                return;
            }
            int size = jsonArray.length();
            for (int i = 0; i < size; i++) {
                CarSource carSource = new CarSource();
                carSource.setModel(jsonArray.getJSONObject(i).getString("model"));
                carSource.setModel_detail(jsonArray.getJSONObject(i).getString("model_detail"));
                carSource.model_detail_zh = jsonArray.getJSONObject(i).getString("model_detail_zh");
                carSource.mMile = jsonArray.getJSONObject(i).getString("mile");
                carSource.model_zh = jsonArray.getJSONObject(i).getString("model_zh");
                carSource.mYear = jsonArray.getJSONObject(i).getString("year");
                carSource.eval_time = jsonArray.getJSONObject(i).getString("eval_time");
                carSource.is_default = jsonArray.getJSONObject(i).getBoolean("is_default");
                carSource.mId = jsonArray.getJSONObject(i).getInt("id");
                carSource.setmCity(jsonArray.getJSONObject(i).getString("city"));
                carSource.mMouth = jsonArray.getJSONObject(i).getString("month");
                carSource.mThumbnail = jsonArray.getJSONObject(i).getString("thumbnail");
                carSources.add(carSource);
            }
            likeCarAdapter.notifyDataSetChanged();
            findViewById(R.id.no_data).setVisibility(View.GONE);
        } catch (Exception e) {
        }
    }
}
